package com.sam.controller;

import com.sam.domain.entity.ChatMessage;
import com.sam.service.IDeepSeekService;
import jakarta.annotation.Resource;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户信息
 *
 * @author <a href="mailto:807837863.qq.com">sam</a>
 * @since 2025-01-18 19:14
 */
@Controller
public class UserController {

    @Resource
    private IDeepSeekService deepSeekService;

    private List<ChatMessage> chatHistory = new ArrayList<>();

    /**
     * 登录页面
     * @return
     */
    @RequestMapping("/")
    public String index(){
        return "login";
    }

    /**
     * 成功页面
     * @return
     */
    @RequestMapping(value = "/success")
    public String success(){
        return "success";
    }

    /**
     * 无权限页面
     * @return
     */
    @RequestMapping("/noPermission")
    public String noPermission(){
        return "noPermission";
    }

    @RequestMapping("/login")
    public String login(String username, String password, Model model){
        //创建一个shiro的Subject对象，利用这个对象来完成用户的登录认证
        Subject subject= SecurityUtils.getSubject();
        //登出方法调用，用于清空登录时的缓存信息，否则无法重复登录
        subject.logout();
        //判断当前用户是否已经认证过，如果已经认证过着不需要认证如果没有认证过则进入if完成认证
        if(!subject.isAuthenticated()){
            //创建一个用户账号和密码的Token对象，并设置用户输入的账号和面
            //这个对象将在Shiro中被获取
            UsernamePasswordToken token=new UsernamePasswordToken(username,password);
            try {
                //例如账号不存在或密码错误等等，我们需要根据不同的异常类型来判断用户的登录状态并给与友好的信息提示
                //调用login后Shiro就会自动执行我们自定义的Realm中的认证方法
                subject.login(token);
            } catch (UnknownAccountException e) {
                //进入catch 表示用户的账号错误，这个异常是我们在后台抛出的
                System.out.println("---------------账号不存在");
                model.addAttribute("errorMessage","账号不存在");
                return "login";
            }catch (LockedAccountException e){
                //进入catch 表示用户的账号被锁定，这个异常是我们在后台抛出的
                System.out.println("===============账号被锁定");
                model.addAttribute("errorMessage","账号被冻结");
                return "login";
            }catch (IncorrectCredentialsException e){
                //进入catch 表示用户的密码，这个异常是shiro在认证密码时抛出
                System.out.println("***************密码不匹配");
                model.addAttribute("errorMessage","密码错误");
                return "login";
            }
        }
        return "redirect:/success";
    }

    @RequestMapping("/user/test")
    public @ResponseBody String userTest(){
        return "这是userTest请求";
    }

    @RequestMapping("/admin/test")
    public @ResponseBody String adminTest(){
        return "这是adminTest请求";
    }

    @RequestMapping("/loginOut")
    public String loginOut(){
        Subject subject= SecurityUtils.getSubject();
        //登出方法调用，用于清空登录时的缓存信息，否则无法重复登录
        subject.logout();
        return "login";
    }

    /**
     * 跳转到增加
     * @return
     */
    @RequiresPermissions("admin:add")
    @RequestMapping("/admin/add")
    public String addpPage(){
        return "add";
    }

    /**
     * 跳转到修改
     * @return
     */
    @RequiresPermissions("admin:update")
    @RequestMapping("/admin/update")
    public String updatePage(){
        return "update";
    }

    @RequiresPermissions("admin:update")
    @RequestMapping("/admin/talk")
    public String chat(Model model) {
        model.addAttribute("messages", chatHistory);
        model.addAttribute("newMessage", new ChatMessage());
        return "chat";
    }

    @RequiresPermissions("admin:update")
    @PostMapping(value = "/admin/chat")
    public String chat(@ModelAttribute ChatMessage newMessage) {
        chatHistory.add(new ChatMessage("user", newMessage.getContent()));
        String response = deepSeekService.getResponse(newMessage.getContent());

        // 添加 AI 回复到历史记录
        chatHistory.add(new ChatMessage("assistant", response));

        return "redirect:/admin/talk";
    }

    @RequiresPermissions("admin:update")
    @RequestMapping("/admin/stream")
    public String streamChat(Model model) {
        model.addAttribute("messages", chatHistory);
        return "stream-chat";
    }

    /**
     * 流式回答
     * @param message
     * @return
     */
    @RequiresPermissions("admin:update")
    @GetMapping(value = "/admin/chatFlux", produces = MediaType.APPLICATION_JSON_VALUE)
    public Flux<ChatResponse> chatFlux(@RequestParam(value = "message") String message) {
        return deepSeekService.chatFlux(message);
    }

    @RequiresPermissions("admin:update")
    @GetMapping("/send-stream")
    public SseEmitter sendStreamMessage(@RequestParam String message) {
        // 添加用户消息
        chatHistory.add(new ChatMessage("user", message));

        return deepSeekService.sendStreamMessage(message);
    }

}
